package cn.xiaolang.thread.threadlocal;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 父子线程传值(通过传递参数形式实现)
 *
 * @author Dean
 * @date 2021-01-20
 */
@Slf4j
public class ParentChildPassValueIssueSolve1 {

    private static final ThreadLocal<TargetUser> threadLocal = new ThreadLocal<>();

    /**
     * 在执行start方法前获取到父线程的值，传递给子线程
     */
    public static void main(String[] args) throws InterruptedException {
        //主线程设置一个值
        threadLocal.set(new TargetUser("dean-parent"));

        //运行子线程
        Thread childThread = new Thread(new RunTask(), "child-thread");
        childThread.start();

        //主线程等待子线程运行完，以便观察主线程中设置的值是否被子线程成功修改
        childThread.join();

        log.info(" parent thread get result:{}", threadLocal.get());
        threadLocal.remove();

    }

    static class RunTask implements Runnable {
        //获取主线程中设置的值
        private final TargetUser originVal = threadLocal.get();

        @Override
        public void run() {

            //打印主线程的值
            log.info("child get from parent by passed :{}", originVal);

            //如果启用了线程（调用start方法），调用get方法是获取不到值的
            log.info("child get from parent directly:{}", threadLocal.get());

            // 修改从父线程获取到的值
            originVal.setName("dean-child");
        }
    }

    @Data
    @AllArgsConstructor
    private static class TargetUser {

        private String name;

    }

}


